package com.iot.manager.ui.fragments;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import com.iot.manager.R;
import com.iot.manager.data.models.DeviceStats;
import com.iot.manager.network.ApiService;
import com.iot.manager.network.RetrofitClient;
import com.iot.manager.network.WebSocketManager;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class DashboardFragment extends Fragment implements WebSocketManager.DeviceStatsListener {
    private TextView tvTotalDevices;
    private TextView tvOnlineDevices;
    private TextView tvOfflineDevices;
    private TextView tvTotalDataPoints;
    //private TextView tvLastUpdate;
    private ApiService apiService;
    private android.widget.ProgressBar progressBar;
    private View errorLayout;
    private View dataLayout;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_dashboard, container, false);
        apiService = RetrofitClient.getInstance().getApiService();
        initViews(view);
        return view;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        
        // 注册WebSocket监听器
        WebSocketManager.getInstance(requireContext()).addStatsListener(this);
        
        // 加载数据
        loadDeviceStats();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        // 移除WebSocket监听器
        WebSocketManager.getInstance(requireContext()).removeStatsListener(this);
    }

    @Override
    public void onDeviceStatsUpdated(int totalDevices, int onlineDevices, int offlineDevices) {
        if (getActivity() == null) return;
        
        getActivity().runOnUiThread(() -> {
            // 更新设备统计信息
            if (tvTotalDevices != null) {
                tvTotalDevices.setText(String.valueOf(totalDevices));
            }
            if (tvOnlineDevices != null) {
                tvOnlineDevices.setText(String.valueOf(onlineDevices));
            }
            if (tvOfflineDevices != null) {
                tvOfflineDevices.setText(String.valueOf(offlineDevices));
            }
            
            // 更新进度条
            if (progressBar != null && totalDevices > 0) {
                int onlinePercentage = (onlineDevices * 100) / totalDevices;
                progressBar.setProgress(onlinePercentage);
            }
        });
    }

    private void initViews(View view) {
        tvTotalDevices = view.findViewById(R.id.tv_total_devices);
        tvOnlineDevices = view.findViewById(R.id.tv_online_devices);
        tvOfflineDevices = view.findViewById(R.id.tv_offline_devices);
        tvTotalDataPoints = view.findViewById(R.id.tv_total_data_points);
        //tvLastUpdate = view.findViewById(R.id.tv_last_update);
        progressBar = view.findViewById(R.id.progress_bar);
        errorLayout = view.findViewById(R.id.errorLayout);
        dataLayout = view.findViewById(R.id.dataLayout);

        view.findViewById(R.id.btnRetry).setOnClickListener(v -> loadDeviceStats());
    }

    private void loadDeviceStats() {
        showLoading(true);
        hideError();
        
        apiService.getDeviceStats().enqueue(new Callback<DeviceStats>() {
            @Override
            public void onResponse(@NonNull Call<DeviceStats> call, @NonNull Response<DeviceStats> response) {
                showLoading(false);
                if (response.isSuccessful() && response.body() != null) {
                    DeviceStats stats = response.body();
                    updateStats(stats);
                    showData();
                } else {
                    String errorMessage = "获取设备统计信息失败";
                    if (response.code() == 401) {
                        errorMessage = "请重新登录";
                    }
                    showError(errorMessage);
                }
            }

            @Override
            public void onFailure(@NonNull Call<DeviceStats> call, @NonNull Throwable t) {
                showLoading(false);
                String errorMessage = "网络错误: " + t.getMessage();
                showError(errorMessage);
            }
        });
    }

    private void updateStats(DeviceStats stats) {
        tvTotalDevices.setText(String.valueOf(stats.getTotalDevices()));
        tvOnlineDevices.setText(String.valueOf(stats.getOnlineDevices()));
        tvOfflineDevices.setText(String.valueOf(stats.getOfflineDevices()));
        tvTotalDataPoints.setText(String.valueOf(stats.getTotalDataPoints()));
        //tvLastUpdate.setVisibility(View.GONE);
    }

    private void showLoading(boolean show) {
        if (progressBar != null) {
            progressBar.setVisibility(show ? View.VISIBLE : View.GONE);
        }
    }

    private void showError(String message) {
        errorLayout.setVisibility(View.VISIBLE);
        TextView errorText = errorLayout.findViewById(R.id.errorText);
        errorText.setText(message);
        dataLayout.setVisibility(View.GONE);
    }

    private void hideError() {
        errorLayout.setVisibility(View.GONE);
        dataLayout.setVisibility(View.VISIBLE);
    }

    private void showData() {
        errorLayout.setVisibility(View.GONE);
        dataLayout.setVisibility(View.VISIBLE);
    }
} 